import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { Sysconstant } from '../sysconstant.enum';
@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.css']
})
export class DetailComponent implements OnInit {

  public books: any;
  book: any;
  isReader = false;
  size: number = 12;
  index: number = 1;
  isLoading = true;
  category: any;

  constructor(private httpClient: HttpClient, private route: ActivatedRoute, private location: Location) { }

  ngOnInit() {
    this.getBookByCtx();
    let that = this;
    window.addEventListener("scroll", () => {
      that.loadMore();
    });
  }
  getBookByCtx() {
    this.isLoading = false;
    this.category = this.route.snapshot.paramMap.get('cid');
    this.httpClient.get(Sysconstant.BASE_URL + "/book/category/" + this.category + "/" + this.index + "/" + this.size).subscribe(data => {
      this.books = data['list'];
      this.isLoading = true;
    }, err => {
      console.log("error");
    }
    )
  }
  loadMore() {
    var pageYOffset = window.pageYOffset;
    var clientHeight = document.documentElement.clientHeight;
    var offsetHeight = document.body.offsetHeight;
    //当滚动到90%的时候去加载
    if (pageYOffset + clientHeight > offsetHeight * 0.9) {
      //scope.shopWorkCanLoad是否可加载,controller中定义
      //scope.shopWorkOnLoad是否正在加载,controller中定义
      if (this.isLoading) {
        this.isLoading = false;
        this.index = this.index + 1;
        let url = Sysconstant.BASE_URL + "/book/category/" + this.category + "/" + this.index + "/" + this.size;
        this.httpClient.get(url).subscribe(data => {
          this.books = this.books.concat(data['list']);
          this.isLoading = true;
        }, error => {
          this.index -= 1;
          console.log("error");
        })
      }
    }

  }
  readMore(id: string) {
    this.httpClient.get(Sysconstant.BASE_URL + "/book/" + id).subscribe(data => {
      this.book = data;
      this.isReader = true;
    }, err => {
      console.log("error");
    })
  }
  goBack(): void {
    this.isReader=false;
    this.location.back();
  }
}
